package assql
{
	import assql.events.SQLErrorEvent;
	import assql.logging.Logger;
	
	public dynamic class SQLToken
	{
		private var responders:Array;
		
		public function SQLToken()
		{
			this.responders = new Array();
		}
		
		public function get numResponders():int {
			return responders.length;
		}
		
		public function hasResponder(responder:SQLResponder):Boolean {
			for ( var i:int=0; i<responders.length; i++ ) {
				if ( responders[i] == responder ) {
					return true;
				}
			}
			return false;
		}
		
		/**
		 * Adds the responder to this SQLToken
		 **/
		public function addResponder(responder:SQLResponder):void {
			if ( !hasResponder(responder) ) {
				responders.push(responder);
			}
		}
		
		/**
		 * Add's a new SQLResponder to this token that only contains a Result Handler
		 **/
		public function addResultHandler(handler:Function):void {
			addResponder(new SQLResponder(null, handler, null, null));
		}
		
		/**
		 * Add's a new SQLResponder to this token that only contains a Response Handler
		 **/
		public function addResponseHandler(handler:Function):void {
			addResponder(new SQLResponder(null, null, handler, null));
		}
		
		/**
		 * Add's a new SQLResponder to this token that only contains a Parameters Handler
		 **/
		public function addParametersHandler(handler:Function):void {
			addResponder(new SQLResponder(null, null, null, handler));
		}
		
		/**
		 * Add's a new SQLResponder to this token that only contains a Error Handler
		 **/
		public function addErrorHandler(handler:Function):void {
			addResponder(new SQLResponder(handler, null, null, null));
		}
		
		assql_internal function callResultHandlers(result:ResultSet):void {
			Logger.Info(this, "Calling Result Handlers");
			
			for each ( var responder:SQLResponder in responders ) {
				responder.assql_internal::callResultHandler(result, this);
			}
		}
		
		assql_internal function callResponseHandlers(response:SQLResponse):void {
			Logger.Info(this, "Calling Response Handlers");
			
			for each ( var responder:SQLResponder in responders ) {
				responder.assql_internal::callResponseHandler(response, this);
			}
		}
		
		assql_internal function callParametersHandlers(params:SQLParameters):void {
			Logger.Info(this, "Calling Parameter Handlers");
			
			for each ( var responder:SQLResponder in responders ) {
				responder.assql_internal::callParametersHandler(params, this);
			}
		}
		
		assql_internal function callErrorHandlers(error:SQLErrorEvent):void {
			Logger.Info(this, "Calling Error Handlers");
			
			for each ( var responder:SQLResponder in responders ) {
				responder.assql_internal::callErrorHandler(error, this);
			}
		}
	}
}